from datetime import timedelta

from gm.api import *


class GmTool:

    def log(self, context: Context, *args):
        if context.mode == MODE_LIVE:
            print(context.now.strftime('%Y-%m-%d %H:%M:%S'), *args)

    def info(self, context: Context, *args):
        print(context.now.strftime('%Y-%m-%d %H:%M:%S'), *args)

    def monitorIndexTrend(self, context: Context, code='SZSE.159531'):
        """监控指数趋势, 1=上升,0=不变,-1=下跌
        """
        # 'SZSE.159531' 中证2000
        # 获取当前日期
        self.log(context, '开始检测指数趋势')
        now = context.now
        todayStr = now.strftime('%Y-%m-%d')
        after1Day = (now + timedelta(days=1)).strftime('%Y-%m-%d')
        pre1Day = (now - timedelta(days=1)).strftime('%Y-%m-%d')
        pre10Day = (now - timedelta(days=10)).strftime('%Y-%m-%d')
        historyMinuteData = history(symbol=code, frequency='60s', start_time=todayStr, end_time=after1Day,
                                    fields='open, close, low, high, eob', adjust=ADJUST_PREV, df=True)
        historyDayData = history(symbol=code, frequency='1d', start_time=pre10Day, end_time=pre1Day,
                                 fields='open, close, low, high, eob', adjust=ADJUST_PREV, df=True)
        preDayClosePrice = historyDayData['close'].iloc[-1]
        todayFirstPrice = historyMinuteData.loc[0]

        trend = 0
        # 交易日9:32分触发
        if preDayClosePrice > todayFirstPrice['open'] > todayFirstPrice['close'] > historyMinuteData.loc[1]['close']:
            trend = -1
        elif preDayClosePrice < todayFirstPrice['open'] < todayFirstPrice['close'] < historyMinuteData.loc[1]['close']:
            trend = 1
        if trend != 0:
            self.info(context, '指数趋势:', trend)
        else:
            self.log(context, '结束检测指数趋势')
        return trend

    def clearStock(self, context, code):
        """
        清仓指定股票
        :param context:
        :param code:
        """
        position = context.portfolio.positions[code]
        # close_position(position)

        pass

    def clearAllPosition(self, context):
        """
        清仓所有股票
        :rtype: object
        """
        for position in context.portfolio.positions:
            self.clearStock(context, position.symbol)
        pass

    def getIndexStock(self, indexCode):
        res = stk_get_index_constituents(indexCode)

    def buy(self, code, amount):
        res = order_volume(symbol=code, volume=100, side=OrderSide_Buy, order_type=OrderType_Market_BOC,
                           position_effect=PositionEffect_Open, price=protect_price)
        print(res)


gmTool = GmTool()
